package TUILayer;//makes this class a part of the TUILayer package
import java.util.Scanner;
import ControlLayer.*;//The TUILayer needs to know the ControlLayer
import ModelLayer.Person;
 

/**
 * User interface class to the AddressBook
 * 
 * @author (kbh) 
 * @version (2005.03.31)
 * (FEN): 2006.03.21: Comments translated into English
 * (FEN): 2006.03.21: Some changes to the architecture in order to assure layering
 *                    and loose coupling
 */
public class AddressBookUI
{   

    private AddressCtr addressCtr;//reference to the ControlLayer
    
    /**
     * Constructor
     */
    public AddressBookUI()
    {
       addressCtr = new AddressCtr();
    }
    
    /**
     * Starts the address menu
     */
    public void start()
    { 
        addressMenu();
    }
    
    /**
     * Address menu loop.
     */
    public void addressMenu()
    {
       boolean exit = false;
       while(!exit)//that is: while exit is false
       {
          int choise = writeAddressBookMenu(); 
          if(choise == 1)
          {   //show person
              showPerson();
          }
          else{
              if(choise == 2){
                    addPerson();
              }  
              else{
                  if(choise == 3){
                      //delete person
                      removePerson();
                  }  
                  else{
                      if(choise == 4){
                          // update person
                          updatePerson();
                      }
                      else{
                          if(choise == 5){
                              // listAllPersons();
                              showAllPersons();
                            }
                          else{
                              exit = true;
                           }//end else
                        }//end else
                    }//end else
                }//end else
            }//end else
            pause();
       }//end while
    }
    
    /**
     * Writes the address book menu text, and prompts for a choise
     * 
     * @return  an int containing the users choise
     */
    public int writeAddressBookMenu()
    {      // makes an object keyboard to read input from the screen
            Scanner keyboard = new Scanner(System.in);
            System.out.println("\f *** AddressBook Menu ***");
            System.out.println(" (1) Show information about person");
            System.out.println(" (2) Add person");
            System.out.println(" (3) Delete person");
            System.out.println(" (4) Update person");
            System.out.println(" (5) List all persons");
            System.out.println(" (6) Return");
            System.out.print("\n Make your choice: ");
            
            int choise = keyboard.nextInt();
            return choise;
        }
        
    /**
     * Asks for an ID for a person, and returns the user input
     */
    public int inputPersonsID()
    {   
        boolean ok = false;
        int id = 0;
        while(!ok)
        {
        // makes an object keyboard to have input from the console
           Scanner keyboard = new Scanner(System.in);
           System.out.println(" Write Id:  ");
           try{
             id = keyboard.nextInt();
             ok = true;
           }
           catch (Exception e)
            {
             System.out.println("Der skal indtastes et tal -  prøv igen");
             String input = keyboard.nextLine();
           }
        }//end while
        return id;
    }
    
    /**
     * Asks for a name for a person, and returns the user input
     */
    public String inputName()
    {
         // makes an object keyboard to have input from the screen
         Scanner keyboard = new Scanner(System.in);  
         System.out.println(" Write Name:  ");
         String name = keyboard.nextLine();
         return name;
    }
    /**
     * Asks for a postal code (zip code) for a person, and returns the user input
     */
    public String inputPostalCode()
    {
         // makes an object keyboard to have input from the screen
         Scanner keyboard = new Scanner(System.in);  
         System.out.println(" Write Postal Code:  ");
         String code = keyboard.nextLine();
         return code;
    }
    
    /**
     * Asks for a city for a person, and returns the user input
     */
    public String inputCity()
    {
         // makes an object keyboard to have input from the screen
         Scanner keyboard = new Scanner(System.in);  
         System.out.println(" Write City:  ");
         String city = keyboard.nextLine();
         return city;
    } 
    
    /**
     * Asks for a phone number for a person, and returns the user input
     */
    public String inputPhone()
    {
         // makes an object keyboard to have input from the screen
         Scanner keyboard = new Scanner(System.in);  
         System.out.println(" Write Phone Number:  ");
         String phone = keyboard.nextLine();
         return phone;
    } 
    
    /**
     * Asks for an address for a person, and returns the user input 
     */
    public String  inputAddress()
    {
        // makes an object keyboard to read input from the console
        Scanner keyboard = new Scanner(System.in);
        System.out.println(" Write Address: ");
        String address = keyboard.nextLine();
        return address;
    }
    
    /**
     * Adds a person to the address book (ie creates a person)
     */
    public void addPerson()
    {
        int id = inputPersonsID();
        String name = inputName();
        String address = inputAddress();
        String zipCode = inputPostalCode();
        String city = inputCity();
        String phoneNumber = inputPhone();
        
        addressCtr.addPerson(id, name, address, zipCode, city, phoneNumber);
    }
    
    /**
     * prints the ID of a person to the screen
     */
    public void showId(int id)
    {
        System.out.println("ID of the person: " + id);

    }
    /**
     * prints the name of a person to the screen
     */
    public void showName(String name)
    { 
        System.out.println("The name of the person: " + name);
  
    }
    /**
     * prints the address of a person to the screen
     */
    public void showAddress(String address)
    { 
        System.out.println("The address of the person: " + address);

    }

    /**
     * Asks for an ID, then returns the person object containing that ID.
     */
    public Person getPerson()
    {
        int id = inputPersonsID();
        Person person = addressCtr.getPerson(id);
        return person;
    } 
    
    /**
     * Finds a person-object with a user-specified ID, and calls printPerson(<Person>)
     */
    private void showPerson()
    {
        int id = inputPersonsID();
        Person person = addressCtr.getPerson(id);
        if(person != null)
        {
            printPerson(person);
        }
    }
    
    /**
     * Calls printPerson(<Person>) for all person-objects
     */
    private void showAllPersons()
    {
        for(Person person : addressCtr.listAllPersons())
        {
            System.out.println("#################");
            printPerson(person);
        }
    }
    
    /**
     * Prints the name, ID and address of the inputted person
     */
    private void printPerson(Person person)
    {
        showName(person.getName());
        showId(person.getId());
        showAddress(person.getAddress());
    }
    
    /**
     * Makes sure that the printed input can be read by
     * requesting a RETURN before continuing.
     */
    private void pause()
    {
        System.out.println("Press RETURN to continue...");
        Scanner keyboard = new Scanner(System.in);
        keyboard.nextLine();
    }
    
    /**
     * Asks for an ID, and removes the person with that ID from the address book
     */
    private void removePerson()
    {
        //get the ID from the user:
        int id = inputPersonsID();
        
        //remove the person with the id from the list:
        addressCtr.removePerson(id);
        
    }
    /**
     * Asks if a person name should be changed. if yes, then the change is returned. If no, 
     * the original name will be returned
     */
    private String editName(String name)
    {
        System.out.println("current name: " + name);
        if(changeYesNo().equals("y"))
        {
            return writeNew("name");    //<-- returns a new name written by the user
        }  
        else
        {
            return name;
        }
    }
    /**
     * Asks if a person ID should be changed. if yes, then the change is returned. If no, 
     * the original ID will be returned
     */
    private int editId(int id)
    {
        System.out.println("Current ID: " + id);
        if(changeYesNo().equals("y"))
        {
            String stringId = writeNew("id");   
            int newId = -1; //<-- "error code"
            //try to parse the stringId to an int
            try 
            {
                newId = Integer.parseInt(stringId);    
            }
            catch(Exception e)
            {
                System.out.println("Error when parsing ID to int!");
            }
            
            //if the id was not changed
            if(newId == -1)
            {
                //then return the old ID
                return id;
            }
            else
            {
                return newId;
            }
        }  
        else
        {
            return id;
        }
    }
    
    /**
     * Asks if a person Address should be changed. if yes, then the change is returned. If no, 
     * the original address will be returned
     */
    private String editAddress(String address)
    {
        System.out.println("Current address: " + address);
        if(changeYesNo().equals("y"))
        {
            return writeNew("address");    //<-- returns a new name written by the user
        }  
        else
        {
            return address;
        }
    }
    
    /**
     * Asks if a person zip code should be changed. if yes, then the change is returned. If no, 
     * the original zip code will be returned
     */
    private String editZipCode(String zipCode)
    {
        System.out.println("Current zip code: " + zipCode);
        if(changeYesNo().equals("y"))
        {
            return writeNew("id");    //<-- returns a new name written by the user
        }  
        else
        {
            return zipCode;
        }
    }
    
    /**
     * Asks if a person city should be changed. if yes, then the change is returned. If no, 
     * the original city will be returned
     */
    private String editCity(String city)
    {
        System.out.println("Current city: " + city);
        if(changeYesNo().equals("y"))
        {
            return writeNew("id");    //<-- returns a new name written by the user
        }  
        else
        {
            return city;
        }
    }
    
    /**
     * Asks if a person phone number should be changed. if yes, then the change is returned. If no, 
     * the original phone number will be returned
     */
    private String editPhoneNumber(String phoneNumber)
    {
        System.out.println("Current phone number: " + phoneNumber);
        if(changeYesNo().equals("y"))
        {
            return writeNew("id");    //<-- returns a new name written by the user
        }  
        else
        {
            return phoneNumber;
        }
    }
    
    /**
     * Creates a new "attribute". e.g, if attribute is equal to "name", then 
     * the user will be prompted to write a new name. After this,
     * the user must confirm by writing "y" or "n".
     * If "y", then the newly written name is returned, else will this
     * method execute itself again, until "y" was written.
     * 
     * @param   attribute   a string representation of which attribute to change, e.g. "name"
     */
    private String writeNew(String attribute)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Write new " + attribute + " here: ");
        String newName = keyboard.nextLine();
        
        System.out.println("Is this ok?");
        String confirm = changeYesNo();
        
        if(confirm.equals("n"))
        {
            return newName;
        }
        else
        {
           return writeNew(attribute);
        }
    }
    
    /**
     * Asks if the user wishes to make a change. Returns "y" or "n"
     */
    private String changeYesNo()
    {
        System.out.println("do you wish to make any changes? (y/n)");
        Scanner keyboard = new Scanner(System.in);
        String answer = keyboard.nextLine();
        
        if(answer.equals("y") || answer.equals("n"))
        {
            return answer;
        }
        else
        {
            System.out.println("please write only \"y\" or \"n\" ");
            return changeYesNo();
        }
    }
    
    /**
     * Updates the person-attribute by calling the edit* methods,
     * then deleting the person i question, and then adds/creates a new person
     * with the changes made to the address book
     */
    private void updatePerson()
    {
        
        Person personToUpdate = getPerson();
        
        
        String name = editName(personToUpdate.getName());
        String address = editAddress(personToUpdate.getAddress());
        String zipCode = editZipCode(personToUpdate.getZipCode());
        String city =  editCity(personToUpdate.getCity());
        String phoneNumber = editPhoneNumber(personToUpdate.getPhoneNumber());
        int id = editId(personToUpdate.getId());
        
        addressCtr.removePerson(personToUpdate.getId());
        addressCtr.addPerson(id, name, address, zipCode, city, phoneNumber);
    }
}
            
        
